<?php
/**
 * 前台商品控制器
 * @version 2014100714
 * @author Max.Yu <max@jipu.com>
 */

namespace Home\Controller;
use Admin\Controller\DatabaseController;
use Think\Cache;
use Think\Db;

class ItemController extends HomeController{

  /**
   * 搜索列表页
   * @param $cid 商品分类
   * @param $label 筛选标签：is_recommend->首页推荐，is_new->新品，is_hot->
   * 热卖，is_promote->特价
   * @param $keyword 关键词
   * @param $_field 排序字段
   * @param $_order 排序
   * @author Max.Yu <max@jipu.com>
   */
  public function search($cid = '', $label = '', $keyword = '', $_field = '', $_order = ''){
    $brand = I('get.brand','');
    $prop  = I('get.prop','');
    $cid = I('get.cid');
    $dqkdh = I('get.dqkdh');
    $uid = $_SESSION['jipushop_home']['user_auth']['uid']?$_SESSION['jipushop_home']['user_auth']['uid']:0;
    $user = D('Addons://StoreSel/StoreSel')->where(array('member_id' => $uid))->find();
    $vid=Db::query("SELECT L.id FROM shante.st_user_live L INNER JOIN shante.st_user u ON u.uid=L.row_id WHERE phone<>'' && phone='{$_SESSION['jipushop_home']['user_auth']['mobile']}'")[0]['id'];
    $item_labels = I('get.item_label');
    if($user!=null&&$user['grade_id']>2&&$user['status']==1||$vid>0){
        $vizprice=1;
    }else{
        $vizprice=0;
    }
    $searchArr = array();
    $where = array('status' => 1);
    //实例化数据模型
    $item_model = M('Item');
    $item_category_model = D('ItemCategory');
    $Store_class_model = D('StoreClass');
    $search_model = D('Search');
    $fav_model = D('Fav');
    $item_label = D('ItemLabel');
    $coupon=I('get.coupon');
    if($coupon){
      $cp=M('coupon')->find($coupon);
      if(!empty($cp['items'])){
        $where['id']=array('in',explode(',',$cp['items']));
      }
    }
    if(!empty($prop)){
        $getProp = explode(',',$prop);
        $selectProp = array();
        $propIds = array();
        foreach ($getProp as $proVal){
            $tmpPro = explode(':',$proVal);
            array_push($selectProp,$tmpPro['0']);
            array_push($propIds,$tmpPro['1']);
        }
        $selectProp = getUniqure($selectProp);
        $propIds = getUniqure($propIds);
        if($propIds){
            $option = M('PropertyOption')->where(array('id'=>array('in',$propIds)))->select();
            $prp_codes = array_column($option,'code');
            $prp_ids = array_column($option,'prp_id');
            if(!empty($prp_ids) && !empty($prp_codes)){
                $mapArr = array();
                foreach ($prp_codes as $codeK=>$codeV){
                    $mapArr[] = '%'.$codeV.'%';
                }
                $specMap['spc_code'] = array('like',$mapArr,'AND');
                $specList = M('ItemSpecifiction')->where($specMap)->select();
                $itemIds = array_column($specList,'item_id');
                if(!empty($itemIds)){
                    $where['id']=array('in',$itemIds);
                }
                
                // 规格
                $spec = M('ItemProperty')->where(array('id'=>array('in',$prp_ids),'type'=>'specification'))->select();
                $spec = arrKeyChange($spec, 'id');
                foreach ($option as $opk=>$opv){
                    $tmpArr['string'] = $spec[$opv['prp_id']]['cname'].'：'.$opv['option'];
                    $tmpArr['type'] = 'prop';
                    $tmpArr['param'] = '';
                    $tmpStr = $opv['prp_id'].':'.$opv['id'];
                    if(in_array($tmpStr,$getProp) && count($getProp) > 1){
                        foreach ($getProp as $proVal){
                            $tmpPro = explode(':',$proVal);
                            array_push($selectProp,$tmpPro['0']);
                            array_push($propIds,$tmpPro['1']);
                            if($tmpStr != $proVal){
                                $tmpArr['param'] .= empty($tmpArr['param']) ? $proVal : ','.$proVal;
                            }
                        }
                    }
                    array_push($searchArr,$tmpArr);
                }
            }
        }
    }
    //设置查询条件：商品分类
    $item_property = array();
    if($cid){
      $where['cid_1|cid_2|cid_3'] = $cid;
      $data_category = $item_category_model->info($cid);
      $meta_title = $data_category['meta_title'];
      // 查询规格
      $proMap['cid'] = $cid;
      $proMap['type'] = 'specification';
      $proMap['is_recommend'] = 1;
      // 规格：单选、复选、下拉框才可以展示，文本框不展示
      $proMap['formtype'] = array('in',array('radio','checkbox','select','image'));
      if(!empty($selectProp)){
          $proMap['id'] = array('not in',$selectProp);
      }
      $item_property = M('ItemProperty')->where($proMap)->select();
      foreach($item_property as $key=>$val){
          $optMap['prp_id'] = $val['id'];
          $item_property[$key]['option'] = M('PropertyOption')->where($optMap)->order('`sort` DESC')->select();
          if(!empty($item_property[$key]['option'])){
              foreach ($item_property[$key]['option'] as $keys=>$vals){
                  if(!empty($prop) && $prop != $vals['id']){
                      $item_property[$key]['option'][$keys]['opt_ids'] = $prop.','.$val['id'].':'.$vals['id'];
                  }else{
                      $item_property[$key]['option'][$keys]['opt_ids'] = $val['id'].':'.$vals['id'];
                  }
              }
          }
      }
      
      // 分类品牌读取
      $bMap['status'] = 1;
      $bMap['cid'] = $cid;
      $bOrder = '`recommend` DESC, `sort` DESC';
      $brandList = M('Brand')->where($bMap)->order($bOrder)->select();

        //获取标签
        $itemLabel = $item_label->getLabel($cid);
        $this->itemLabel = $itemLabel;
        $cate_active['item_label'][$item_labels] = 'current';    
    }else{
        // 所有品牌读取
        $bMap['status'] = 1;
        $bOrder = '`recommend` DESC, `sort` DESC';
        $brandList = M('Brand')->where($bMap)->order($bOrder)->select();
    }
    
    if(!empty($brand)){
        $brandIds = explode(',',$brand);
        $where['brand_id']=array('in',$brandIds);
        // 查询品牌
        $brandMap['status'] = 1;
        $brandMap['id'] = array('in',$brandIds);
        $brandSearch = M('Brand')->where($brandMap)->select();
        $tmpBrand['string'] = '品牌：';
        $tmpBrand['type'] = 'brand';
        $tmpBrand['param'] = '';
        $brandCount = count($brandSearch);
        foreach ($brandSearch as $bKey=>$bVal){
            $tmpBrand['string'] .= ($brandCount-1 > $bKey) ? $bVal['name'].'、' : $bVal['name'];
        }
        array_push($searchArr,$tmpBrand);
    }

    //设置查询条件：商品标注&标签&特征
    if($label){
      $label_key = array(
        'index' => array('is_recommend', '推荐'),
        'new' => array('is_new', '新品'),
        'hot' => array('is_hot', '热卖'),
        'promote' => array('is_promote', '特价')
      );
      if($res = $label_key[$label]){
        $where[$res[0]] = 1;
        $meta_title = $res[1];
      }
    }

    $meta_title = strFilter($keyword);

    if($dqkdh){
        $where['dqkdh'] = true;
    }

    //先搜索标签
    if($keyword){
        $lMap['cname'] = array('LIKE','%'.$keyword.'%');
        $labes_id = M('ItemLabel')->where($lMap)->field('id')->select();
        if($labes_id){
            $key_arr = end($labes_id);
            $where['_string'] .= "((";
            foreach($labes_id as $v){
                if($key_arr['id'] == $v['id']){
                    $where['_string'] .= 'FIND_IN_SET("'.$v['id'].'" , item_label)';
                }else{
                    $where['_string'] .= 'FIND_IN_SET("'.$v['id'].'" , item_label)' . " OR ";
                }
            }

            $where['_string'] .= ") OR `name` like '%{$keyword}%')";
        }else{
            $where['name'] = array('LIKE', '%'.$keyword.'%');
        }
    }
    //如果有商品标签
    if($item_labels){
        $where['_string'] = 'FIND_IN_SET("'.$item_labels.'" , item_label)';
    }
    //根据查询条件查询商品数据
    $order = '`is_top` desc, `sort` asc, `id` desc';
    if(I('get._field')) $order='`'.I('get._field').'` '.I('get._order').', '.$order;
    if(C('START_POSITION') && session('zone.id')){
      $city = session('zone.district') ? session('zone.district') : session('zone.id');
      if($where['_string']){
        $where['_string'] .= ' AND FIND_IN_SET("'.$city.'" , set_zone)';
      }else{
        $where['_string'] = 'FIND_IN_SET("'.$city.'" , set_zone)';
      }
    }
    //将商户ID加入
    if (I('get.store_id')) {
      $where['store_id'] = I('get.store_id');
    }
    //店铺禁用 商品不展示
    $store_ids = M('Store')->where('status=0')->getField('store_id',true);
    if(!empty($store_ids)){
      $where['store_id'] = array('NOT IN',$store_ids);
    }
    $lists = $this->lists($item_model, $where, $order, true, 24);
    //搜索结果加入索引
    if($keyword && !$has_keyword && $lists){
      $item_ids = get_sub_by_key($lists, 'id', '', true);
      //搜索结果加入索引
      $data = array(
        'keyword' => $keyword,
        'result' => $item_ids,
        'num' => 1,
      );
      $search_model->update($data);
    }

    //获取分类数据
    if(empty($cid))$cid=0;
    
    //获取当前类所在层级
    $cates[]=array('item'=>$item_category_model->getChild($cid),'pid'=>$cid,'cid'=>0);
    $cate_active[$cid][0] = 'current';
    
    if(count($cates[0]['item'])==0)$cates=array();
    $pid=$cid;
    while($pid>0){
        $item_info=$item_category_model->info($pid);
        $item_tmp=$item_category_model->getBrother($pid);
        $cate_active[$item_tmp[0]['pid']][$pid] = 'current';
        $cates[]=array('item'=>$item_tmp,'cid'=>$pid,'cname'=>$item_info['name'],'pid'=>$item_tmp[0]['pid']);
        $pid=$item_tmp[0]['pid'];
    }
    $cates=array_reverse($cates);
    
    //设置当前排序条件的活动样式
    $order_css['active'][I('get._field')][I('get._order')] = 'active';

    //获取当前用户收藏商品数据和封面图片路径
    $fav_list = $fav_model->listUserFav(UID, 'item');
    if($lists && is_array($lists)){
      foreach($lists as $key => &$value){
        if($value['thumb']){
          $value['cover_path'] = get_cover($value['thumb'], 'path');
        }
        if(!$value['buynum']){
          $value['buynum'] = 0;
        }

        //判断收藏状态
        if($fav_list && is_array($fav_list)){
          $value['is_fav'] = (in_array($value['id'], $fav_list)) ? 1 : 0;
        }else{
          $value['is_fav'] = 0;
        }
      }
    }
    //记录当前页面URL地址Cookie
    Cookie('__forward__', $_SERVER['REQUEST_URI']);
    //模板输出变量赋值
    $this->category = $cates;
    $this->show_child=1;
    $this->cateTree=$item_category_model->getTree();
    $this->assign('brandList',$brandList);
    $this->assign('searchArr',$searchArr);
    $this->cate_active = $cate_active;
    $this->cid = $cid;
    $this->brand = $brand;
    $this->prop = $prop;
    $this->label = $label;
    $this->keyword = htmlspecialchars($keyword);
    $this->_field = $_field;
    $this->_order = $_order;
    $this->order = $order;
    $this->lists = $lists;
    $this->order_css = $order_css;
    $this->meta_title = $meta_title;
    $this->item_label = $item_labels;
    $this->assign('item_property',$item_property);
    $this->assign('vizprice',$vizprice);
    $this->assign('uid',$uid);
    IS_AJAX ? $this->display('itemList') : $this->display();
  }
  
  
  /**
   * 搜索品牌
   */
  public function ajaxBrand(){
      $cid = I('cid');
      $key = trim(I('key'));
      $prop = I('prop');
      $label = I('label');
      $keyword = I('keyword');
      $_field = I('_field');
      $_order = I('_order');
      if(empty($key)){
          $this->error('搜索词不能为空！');
      }
      // 所有品牌读取
      $map['status'] = 1;
      $map['name'] = array('like','%'.$key.'%');
      $order = '`recommend` DESC, `sort` DESC';
      $brandList = M('Brand')->where($map)->order($order)->select();
      
      $this->assign('cid',$cid);
      $this->assign('prop',$prop);
      $this->assign('label',$label);
      $this->assign('keyword',$keyword);
      $this->assign('_field',$_field);
      $this->assign('_order',$_order);
      $this->assign('brandList',$brandList);
      $rtn['html'] = $this->fetch();
      $rtn['status'] = 1;
      exit(json_encode($rtn));
  }

  /**
   * 商品详情页
   * @author Max.Yu <max@jipu.com>
   */
  public function detail($id = 0){
      $uid = $_SESSION['jipushop_home']['user_auth']['uid']?$_SESSION['jipushop_home']['user_auth']['uid']:0;
      $user = D('Addons://StoreSel/StoreSel')->where(array('member_id' => $uid))->find();
      $vid=Db::query("SELECT L.id FROM shante.st_user_live L INNER JOIN shante.st_user u ON u.uid=L.row_id WHERE phone<>'' && phone='{$_SESSION['jipushop_home']['user_auth']['mobile']}'")[0]['id'];
      $item_labels = I('get.item_label');
      if($user!=null&&$user['grade_id']>2&&$user['status']==1||$vid>0){
          $vizprice=1;
      }else{
          $vizprice=0;
      }


      if(isset($_GET['is_app']) && $_GET['is_app'] == 'y'){
      session('IS_APP',true);
    }
    //验证参数的合法性
    if(!(is_numeric($id) && $id > 0)){
      $this->error('参数非法！');
    }
    
    //实例化数据模型
    $item_model = D('Item');
    //获取商品数据
    $data = $item_model->detail($id);

    //记录当前页的前一页URL地址是否存在
    if(is_weixin()){
      if ($_SERVER['HTTP_REFERER'] != null) {
        $this->lastUrl = 1;
        Cookie('vistUrl',0);
      }else{
        $this->lastUrl = 0;
        Cookie('vistUrl',1);
      }
    }

    if(empty($data)){
      $this->error('商品不存在！', U('/'));
    }elseif($data['status'] <= 0){
      $this->error('该商品已下架！', U('/'));
    }
    if(C('START_POSITION') && !checkzone_cache($id)){
      $this->error( '该商品不在本销售区域，无法查阅' , U('Index/index'));
      die;
    }
    //如果有规格，库存为规格的
    $data['property']['stock'] && $data['stock'] = $data['property']['stock'];
    //获取商品评价数据
    $data['comment'] = D('ItemComment')->lists(array('item_id' => $id, 'status' => array('gt', 0)));

    //获取商品评价数量
    if($data['comment']){
      $data['comment_total'] = count($data['comment']);
      //获取商品评价回复
      foreach($data['comment'] as $k => $v){
        $data['comment'][$k]['reply'] = D('ItemComment')->detail(array('pid' => $v['id']));
      }
    }else{
      $data['comment_total'] = 0;
    }

    //获取左侧相关商品列表：当前分类下的按销量排序
    if($data['cid_1']){
      $map_relative = array(
        'cid_1' => $data['cid_1'],
        'id' => array('NEQ', $data['id']),
        'buynum' => array('GT', 0),
      );
      if(C('START_POSITION') && session('zone.id')){
        $city = session('zone.district') ? session('zone.district') : session('zone.id');
        $map_relative['_string'] = 'FIND_IN_SET("'.$city.'" , set_zone)';
      }
      $data['relative'] = D('Item')->lists($map_relative, 'id, name, price, mprice, thumb, buynum', 'buynum DESC', 6);
    }

    //赠品
    $data['send_item'] = A('Item', 'Event')->getSendItems(array(array($data['id'])), false);
    if($data['send_item']){
      $data['send_min_num'] = M('BuySend')->where(array('item_id' => $data['id'], 'status' => 1))->getField('min_num');
    }

    //满减
    $manjian = A('Order','Event')->getManjianRule($data['store_id']);
    if ($manjian != NULL) {
        $data['manjian']['m'] = array_keys($manjian);
        $data['manjian']['j'] = array_values($manjian);
    }

    //第二件折扣
    //判定过期时间，如果过期禁用此活动
    $SecondPieces = M('SecondPieces')->where(array('item_id'=>$id,'status'=>1))->find();
    $now_time = NOW_TIME;
    if($now_time>$SecondPieces['expire_time']){
       M('SecondPieces')->where(array('item_id'=>$id))->setField('status',0);
    }
    $data['SecondPieces'] = A('Order', 'Event')->getSecondPiecesItemIds($id);
    $data['SecondPieces'] = $data['SecondPieces'][$id];

    //秒杀
    $data['seckill'] = A('Item', 'Event')->getSeckill($id);
   
    //是否开启复购
    $data['fugou_dis_price'] = A('Fugou', 'Event')->getDisPrice($data['id']);

    //更新浏览次数
    $item_model->where(array('id' => $id))->setInc('viewnum');

    //记录当前页URL地址Cookie
    Cookie('__forward__', $_SERVER['REQUEST_URI']);

    //是否显示优惠信息
    $data['show_preferential'] = $data['manjian'] || $data['SecondPieces'] || $data['fugou_dis_price'] > 0;
    
    //商品详情懒加载替换
    $data['intro'] = img_lazy_replace($data['intro']);
    
    $data['category'] = '';
    //分类处理
    if($data['cid_1']){
        $data['category'] = M('item_category')->where(array('id'=>$data['cid_1']))->getField('name');
    }
    if($data['cid_2']){
        $data['category'] .= '/'. M('item_category')->where(array('id'=>$data['cid_2']))->getField('name');
    }
    if($data['cid_3']){
        $data['category'] .= '/'. M('item_category')->where(array('id'=>$data['cid_3']))->getField('name');
    }
    // 店铺信息
    $storeMap['store_id'] = $data['store_id'];
    $storeMap['status'] = 1;
    $store = M('Store')->where($storeMap)->find();

      $nickname=Db::query("SELECT nickname FROM `jipu_member` WHERE uid='{$store['member_id']}'")[0]['nickname'];
      $itemid=$id;

    //获取店铺的优惠券信息列表
    $coupon_list = $this->couponList($data['store_id'],$id);

    //获取商品的标签 BUDDHA 20170626
    if (!empty($data['item_label'])) {
      $label_list = M('ItemLabel')->where("FIND_IN_SET(id,'".$data['item_label']."')")->field('cname')->select();
      $labels = array_column($label_list,'cname');
    }else{
      $labels = '';
    }

    $share = array(
      'title' => $data['name'].'&yen;'.$data['price'],
      'desc' => $data['summary'],
      'img_url' => SITE_URL.$data['cover_path'],
      'link' => SITE_URL.U('Item/detail', array('id' => $data['id'], 'sdp_secret' => SHOP_SECRET))
    );
    // 区域价格 
    if(C('START_POSITION')){
      if(checkzone($id)){
        $zone_id = getZonebyItem($id);
        if($zone_id && $temp_spec = M("ItemZone")->where('zone_id = '.$zone_id .' and item_id='.$id)->select()){
          if($data['property']['tempSpecData']){
            foreach($temp_spec as $k => $v){
              $temp_spec[$k]['is_kill'] = $data['property']['tempSpecData'][$v['spc_code']]['is_kill'] ;
              $temp_spec[$k]['quantity'] = $data['property']['tempSpecData'][$v['spc_code']]['quantity'] ;
              unset($temp_spec[$k]['zone_id']);
            }
            $data['property']['spc_data'] = json_encode($temp_spec);
          }else{
            $data['price'] = $temp_spec[0]['price'];
          }
        }
      }else{
        if($data['property']['tempSpecData']){
          foreach($data['property']['tempSpecData'] as $k => $v){
            $data['property']['tempSpecData'][$k]['quantity'] = 0;
          }
          $data['property']['spc_data'] = json_encode($data['property']['tempSpecData']);
          $data['property']['stock']    =  0;
        }else{
          $data['stock'] = 0;
        }
        $this->zone_id   = $zone_id;
        $this->zone_out  = 1 ;
      }
    }
    //判断是否为秒杀产品，获取秒杀价格
      $item_ids = explode(',',$data['seckill']['item_ids']);
      $map['item_id'] = array('in',$item_ids);
      $map['status'] = 1;
      $lists = M('SeckillItem')->where($map)->getField('id,item_id');
      if(in_array($data['id'],$lists)){
          $data['is_seckill'] =1;
      }

    if(!$data['is_seckill']){
        $data['seckill'] = '';
    }

      $seckill_idKeys=array();
      if($data['seckill']){
          $map['activity_id'] = $data['seckill']['id'];
          $map['status']   = 1;
          $map['item_id']  = $id ;
          $seckill_spec = M('seckill_item_spec')->where($map)->field('spc_code ,quantity,item_id,item_price')->select();

          $param['status'] = 1;
          $param['item_id'] = $id;
          $spec_data = M('ItemSpecifiction')->where($param)->field('spc_code ,price,quantity,item_id')->select();
          foreach($spec_data as $k => $v){
              $spec_data[$k]['item_price'] = $v['price'];
              unset($spec_data[$k]['price']);
          }
         foreach($spec_data as $key => $val){
             $map['spc_code'] = $val['spc_code'];
             $rs = M('seckill_item_spec')->where($map)->field('spc_code ,quantity,item_id,item_price')->find();
           if($rs){
               $seckill_spec[$key] = $rs;
           } else{
               $seckill_spec[$key] = $val;
           }
         }
          if($seckill_spec && is_array($seckill_spec)){
              foreach ($seckill_spec as $key => $val){

                  $val['is_kill'] = 1;
                  //为了避免出现负数
                  $val['price'] = $val['item_price'];
                  $val['quantity'] = ($val['quantity'] >=0 )? $val['quantity'] : 0;
                  $spc_data[$val['spc_code']] = $val;
              }

              $data['property']['spc_data'] = json_encode($spc_data);
          }else{
              $data['price'] = M('SeckillItem')->where(array('status'=>1,'item_id'=>$id))->getField('item_price');
              $data['stock'] = M('SeckillItem')->where(array('status'=>1,'item_id'=>$id))->getField('item_stock');
          }
      }
      unset($data['property']['tempSpecData']);
    //判断登录用户是否是分销商
    if( (C('SDP_PRICE_SHOW') == 1) && SHOP_SECRET){
        //避免多规格不同价格
        $sdp_price = M('Item')->where('id='.$id)->getField('price');
        $sdp_fee = ($data['sdp_type'] == 0) ? sprintf('%.2f',$data['sdp']) : sprintf('%.2f',$data['sdp']*$sdp_price/100);
        $this->sdp_fee = ($sdp_fee >= 0.01) ? $sdp_fee : 0;
        $map = array(
            'secret' => SHOP_SECRET,
            '_string' => "FIND_IN_SET(".$id.",item_ids)"
        );
        $result = M('Shop')->where($map)->find();
        if(!$result){
          $this->is_can_secret = "1";
        }else{
          $this->is_can_secret = "0";
        }
    }
     //判断是否APP
    $this->is_app = is_app() ? 1 : 0;
    $this->data = $data;
    $this->meta_share = $share;
    $this->meta_title = $data['name'];
    $this->coupons = $coupon_list;
    $this->label = $labels;
    $this->assign('store',$store);
    $this->assign('uid',$uid);
    $this->assign('itemid',$itemid);
    $this->assign('nickname',$nickname);
    $this->assign('vizprice',$vizprice);
    // 是否直接跳往购买商品
    $this->assign('buy', I('buy') ?: 0);
    $this->display();
  }

  /**
   * 获取店铺可用优惠券
   * @author buddha <[email address]>
   * @return [type] [description]
   */
  public function couponList($store_id,$item_id){
    //获取可用优惠券
    $map = array(
      'expire_time' => array('gt', NOW_TIME ),
      'is_show'     => 1,
      'store_id'    => $store_id,
      '_string'     => 'FIND_IN_SET('.$item_id.',items) OR items = ""'
    );
    $field = 'id, number, name, amount, norm, expire_time, num,store_id,items';
    $lists = D('Coupon')->lists($map, $field);

    //获取当前用户未领取的优惠券
    $map_coupon_user['uid'] = UID;
    $coupon_user = D('CouponUser')->lists($map_coupon_user, 'coupon_id');
    $coupon_user_ids = get_sub_by_key($coupon_user, 'coupon_id');
    
    foreach($lists as $key =>$value){
        foreach($coupon_user_ids as $val){
           if($value['id'] == $val){
               unset($lists[$key]);
           }
        }
    }

    return $lists;
  }

  /**
   * 分类列表页
   * @author Max.Yu <max@jipu.com>
   */
  public function category(){
    //请求页面传递参数
    $cid = I('get.cid');

    //实例化数据模型
    $item_category_model = D('ItemCategory');

    //定义meta_title
    $meta_title = '商品分类';

    if(!$cid){
      $cid = $category[0]['id'];
    }
    //判断分类展示信息
    if (is_mobile() && C('RECOMMENDED_SHOP') && $_SESSION['jipushop_home']['selected_store_id']) {
      $category = D('Shop/ItemCategory')->getTree(0,true,$_SESSION['jipushop_home']['selected_store_id']);
    }else{
      $category = $item_category_model->getTree();
    }

    //记录当前页URL地址Cookie
    Cookie('__forward__', $_SERVER['REQUEST_URI']);
    //模板输出变量赋值
    $this->category = $category;
    $this->meta_title = $meta_title;
    //if(empty($cid))$cid = $category[0]['id'];
    $this->assign('cid',$cid);
    $this->display();
  }
  
  
  /**
   * 品牌列表页
   */
  public function brand(){
      $map['status'] = array('eq',1);
      $map['recommend'] = 1;
      $order = '`id` ASC';
      $lists = $this->lists('Brand', $map,$order,true,16);
      //记录当前列表页的Cookie
      Cookie('__forward__', $_SERVER['REQUEST_URI']);
      // 按字母查询
      $letter = I('key','');
      $data = array();
      $search = array();
      if(!empty($letter)){
          $where['status'] = array('eq',1);
          $where['letter'] = strtoupper($letter);
          $search = $this->lists('Brand', $where,$order,true,1000);
      }else{
          $where['status'] = array('eq',1);
          $where['letter'] = array('neq','');
          $order = '`letter` ASC';
          $search = $this->lists('Brand', $where,$order,true,1000);
          foreach ($search as $key=>$val){
              $data[$val['letter']][] = $val;
          }
      }
      
      $this->assign('lists',$lists);
      $this->assign('search',$search);
      $this->assign('letter',$letter);
      $this->assign('data',$data);
      $this->meta_title = '品牌列表';
      $this->display();
  }
  //区域价格 ajax获取商品价格sean status 1 成功 2 无相关产品 3没开启区域价格功能
  public function handle_zoneprice(){
    if( IS_AJAX ){
      $info['status'] = 3;
      if(!C('START_POSITION'))return $info;
      $buy = I('buy');
      $order = D('Order');
      $city  = I('city');
      cookie('zone_city' , $city);
      $info['status'] = 1;
      $cart_ids = I('cart_ids');
      $item_ids = I('item_ids');
      if($buy){
        $type = $buy == 2  ? '__joinnow__': '__buynow__';
        $buynow_cookie = cookie($type);
        $goods = array(unserialize($buynow_cookie));
      }else{
        $map['id'] = array('in' , $cart_ids);
        $map['uid']     = UID;
        $goods = M('Cart')->where($map)->field('item_id,item_code,quantity,store_id')->select();
      }
      $dis_price = array();
      foreach($goods as $k => $v){
        if(!checkzone($v['item_id'] , $city)){
          $goods[$k]['zone_out'] = 1;
          $info['status'] = 2;
        }
        if($type != '__joinnow__' ){
          $goods[$k]['price'] = $order->getItemPrice($v['item_id'] , $v['item_code'], false , $city );
          //第二件折扣
          $second_discount = $order->getSecondItemsPrice($v['item_id']);
          $goods[$k]['second_price'] = $second_discount * $goods[$k]['price'];
        }
          if($buy == 3){
              $goods[$k]['price'] = $order->getItemPrice($v['item_id'] , $v['item_code'], true , $city );
          }
        $goods[$k]['stock'] = $order->getItemStock($v['item_id'] , $v['item_code']);
        if($goods[$k]['stock'] == 0){
          $goods[$k]['zone_out'] = 1;
        }
        //复购优惠金额
        if(!in_array($v['item_id'], $dis_prices)){
          $dis_price = A('Fugou', 'Event')->getDisPriceByUser($v['item_id'], UID);
        }else{
          $dis_price = $dis_prices[$v['item_id']];
        }
        $item_price = $dis_price + $goods[$k]['price'];
        if($goods[$k]['price'] && !$buy){
          M('Cart')->where('uid ='.UID.' and item_id ='.$v['item_id'].' and item_code = "'.$v['item_code'].'"' )->save(array('price' => $item_price));
        }
        if($buy){
          unset($goods[$k]['spec']);unset($goods[$k]['code']);
        }
      }
      foreach ($goods as $key => $value) {
        $store[] = $value['store_id'];
      }
      $info['store_num'] = count(array_unique($store));
      $info['goods'] = $goods;
      $this->ajaxReturn($info);
    }
  }

}
